#include "head_s.h"

int download(const user_t* status, int net_fd, MYSQL* mysql)
{
    char file_name[60] = {0};
    char file_path[128] = {0};
    sprintf(file_name, "%s", status->arg);
    LOG_WRITE(LOG_DEBUG, "%s", status->path);
    sprintf(file_path, "%s%s",  status->path, file_name);
    LOG_WRITE(LOG_DEBUG, "%s", file_path);

    //根据用户名在用户表查询用户id
    char search_id[128] = {0};
    sprintf(search_id, "select id from user_info where name = '%s'", status->user_name);
    if (mysql_query(mysql, search_id))
    {
        printf("%s\n", mysql_error(mysql));
    }
    MYSQL_RES* result;
    result = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(result);
    int user_id = atoi(row[0]);
    mysql_free_result(result);
    
    //根据用户id在文件表查找对应文件名的哈希值
    char search_hash[255] = {0};
    sprintf(search_hash, "select file_hash from file_info "
                         "where user_id = %d and file_name = '%s' and file_path = '%s'",
                          user_id, file_name, file_path);
    if (mysql_query(mysql, search_hash))
    {
        printf("%s\n", mysql_error(mysql));
    }
    result = mysql_store_result(mysql);
    my_ulonglong row_num = mysql_num_rows(result);
    //无对应文件
    if (result == NULL || row_num == 0)
    {
        send(net_fd, "1", 1, MSG_NOSIGNAL);
        return -1;
    }
    
    send(net_fd, "0", 1, MSG_NOSIGNAL);
    row = mysql_fetch_row(result);
    char hash[128] = {0};
    sprintf(hash, "%s%s", status->base_path, row[0]);
    
    mysql_free_result(result);
    
    int file_fd = open(hash, O_RDWR);
    int file_name_len = strlen(file_name);
    send(net_fd, &file_name_len, sizeof(int), MSG_NOSIGNAL);
    send(net_fd, file_name, file_name_len, MSG_NOSIGNAL);
    
    struct stat st;
    fstat(file_fd, &st);
    size_t file_size = st.st_size;
    send(net_fd, &file_size, sizeof(size_t), MSG_NOSIGNAL);
    ssize_t ret = sendfile(net_fd, file_fd, 0, file_size);
    LOG_WRITE(LOG_ERROR, "sendfile发送的字节数：%ld", ret);

    return 0;
}
